#include "hotspot.h"


Hotspot::Hotspot()
{
    init_gui();
    if (WiFi.getMode()!=WIFI_AP)
    {
        is_ap = false;
        show_msg(LV_SYMBOL_WARNING, String("AP"), String("Close"));
        
    }
    else{
        is_ap=true;
        num_sta = WiFi.softAPgetStationNum();
        show_msg(LV_SYMBOL_WIFI, WiFi.softAPSSID(), String(num_sta));
    }
}

void Hotspot::init_gui()
{
    label_scr = lv_obj_create(NULL, NULL);
    lv_obj_set_style_local_bg_color(label_scr, LV_OBJ_PART_MAIN, LV_STATE_DEFAULT, LV_COLOR_BLACK);
	lv_scr_load(label_scr);

    lv_style_init(&font_style);
	lv_style_set_text_font(&font_style, LV_STATE_DEFAULT, &lv_font_montserrat_34);
	lv_style_set_text_color(&font_style, LV_STATE_DEFAULT, LV_COLOR_WHITE);

    label_msg = lv_label_create(label_scr, NULL);
    label_sym = lv_label_create(label_scr, NULL);
    label_ssid = lv_label_create(label_scr, NULL);
	lv_obj_add_style(label_msg, LV_LABEL_PART_MAIN, &font_style);
    lv_obj_add_style(label_sym, LV_LABEL_PART_MAIN, &font_style);
    lv_obj_add_style(label_ssid, LV_LABEL_PART_MAIN, &font_style);
}

void Hotspot::open_ap()
{
    if(WiFi.status()==WL_CONNECTED)
        WiFi.disconnect();
    WiFi.mode(WIFI_AP);
    IPAddress softLocal(192,168,4,1);//IP地址，用来设置IP第四字段
    IPAddress softGateway(192,168,4,1);//IP网关，用来设置IP第三字段
    IPAddress softSubnet(255,255,255,0);//配置自定义IP信息
    WiFi.softAPConfig(softLocal, softGateway, softSubnet);
    WiFi.softAP(ssid.c_str());
    is_ap = true;
    show_msg(LV_SYMBOL_WIFI, WiFi.softAPSSID(), String(num_sta));
}

void Hotspot::close_ap()
{
    WiFi.softAPdisconnect(true);
    WiFi.mode(WIFI_OFF);
    is_ap = false;
    show_msg(LV_SYMBOL_WARNING, String("AP"), String("Close"));
}

Event Hotspot::main_process(Action act)
{
    if(is_ap)
    {
        if (act==TURN_LEFT)
        {
            close_ap();
        }
        else{
            tem_num_sta = WiFi.softAPgetStationNum();
            if(num_sta != tem_num_sta)
            {
                num_sta = tem_num_sta;
                show_msg(LV_SYMBOL_WIFI, WiFi.softAPSSID(), String(num_sta));
            }
        }
        event = GREEN;
    }
    else{
        if (act==TURN_RIGHT)
        {
            open_ap();
        }
        event = RED;
    }
    return event;
}

void Hotspot::show_msg(String sym, String msg, String ssid)
{
    lv_label_set_text(label_msg, msg.c_str());
    lv_label_set_text(label_sym, sym.c_str());
    lv_label_set_text(label_ssid, ssid.c_str());
    lv_obj_align(label_msg, NULL, LV_ALIGN_CENTER, 0, 0);
    lv_obj_align(label_sym, NULL, LV_ALIGN_CENTER, 0, -50);
    lv_obj_align(label_ssid, NULL, LV_ALIGN_CENTER, 0, 50);
    lv_task_handler();
}

Hotspot::~Hotspot()
{
    lv_obj_del(label_scr);
}